package person.wend.springbootlearnexample.controller;
import jakarta.validation.Valid;
import jakarta.validation.constraints.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import java.util.Locale;

@Controller
public class SimpleMessageSourceController {
    @Autowired
    private MessageSource messageSource;

    @GetMapping("/form")
    public ModelAndView showForm() {
        return new ModelAndView("form");
    }

    @PostMapping("/submit")
    public ModelAndView submitForm(@RequestParam("name") @Valid @NotNull String name, BindingResult bindingResult) {
        ModelAndView modelAndView = new ModelAndView();
        if (bindingResult.hasErrors()) {
            for (FieldError fieldError : bindingResult.getFieldErrors()) {
                // 获取错误消息代码
                String errorCode = fieldError.getCode();
                // 使用 MessageSource 解析错误消息代码
                String errorMessage = messageSource.getMessage(errorCode, null, Locale.getDefault());
                modelAndView.addObject(fieldError.getField() + "Error", errorMessage);
            }
            modelAndView.setViewName("form");
        } else {
            modelAndView.setViewName("success");
        }
        return modelAndView;
    }
}
